package net.tribal.comic.controllers

import net.tribal.comic.entities.User
import net.tribal.comic.services.AutenticateService

class AutenticateController {
	def autenticateService
	def mailService
	
    def index = { redirect(action:show,params:params) }

    def show = { 
		render(view:'login') 
    }

    def login = {
        if (params?.alias && params?.password ) {
			def userInstance = autenticateService.validate(params.alias,params.password)
			flash.message = "wellcome.user"
			flash.args = [userInstance.id]
			flash.defaultMessage="WELLCOME ${userInstance.alias}"
			session['user'] = userInstance
			redirect(controller:"note", action:"list")
        } else{        	
        	def user = new User()
			user.errors.rejectValue("alias", "reminder.password.no.alias", null, "INTRODUZCA UN ALIAS Y PASSWORD CORRECTOS")
			user.errors.rejectValue("password", "", null, "")
	        render(view: "login", model: [userInstance:user])
		}
    }
	
	/**
	 * Return previus page
	 */
    def cancel = {
    	println "BACK"
		redirect(controller:"note", action:"list")
    }
	
	
	/**
	 * Remove user from session
	 */
    def logout = {
		session.invalidate()
		redirect(controller:"note", action:"list")
	}
    
    /**
     * Send mail to your user account with the user password
     */
    def reminderPassword = {
		def user = User.findByAlias(params.alias)
		println "reminderPassword de autenticate controller" + user
		if (user) {
			try {
				mailService.sendMail {     
				  to user.email
				  subject "tu password"
				  body user.password
				  //"your.password.subject"
				  //'your.password.begin' + user.password + 'your.password.end' 
				}
				flash.message = "password.send"
        		flash.defaultMessage="SE HA ENVIADO SU PASSWORD A SU DIRECCION DE CORREO"
        		redirect(controller:"note", action:"list")
				
			} catch (e) {
				log.error e
				user = new User()
				user.errors.rejectValue("alias", "tecnic.problem", null, "PROBLEMAS TECNICOS")
				render(view: "login", model: [userInstance:user])
			}
		} else {
			user.errors.rejectValue("alias", "reminder.password.no.alias", null, "INTRODUZCA UN ALIAS CORRECTO")
			render(view: "login", model: [userInstance:user])
		}
	}
}